package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.service.ord.pos.vo.KitePosOfferInstVO;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.common.util.SeqUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttachmentDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDiscountDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosSceneHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.cucc.service.util.ChangeTypeUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstDiscount;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.SpringUtil;

@Service
public class KitePosDiscountHandler implements IKitePosSceneHandler {

    @Override
    public void handle(KitePosHandlerContext context) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        List<KitePosDiscountDTO> discountList = new ArrayList<>();

        List<KiteOfferInst> offerInsts = Lists.newArrayList();
        Map<String, KitePosOfferInstVO> mainOfferInstMap = context.getPosSceneBO().getMainOfferInstMap();
        Map<String, KitePosOfferInstVO> giftOfferInstMap = context.getPosSceneBO().getGiftOfferInstMap();
        if (!KiteMapUtils.isEmpty(giftOfferInstMap)) {
            Iterator<KitePosOfferInstVO> iterator = giftOfferInstMap.values().iterator();
            while (iterator.hasNext()) {
                KitePosOfferInstVO offerInstVO = iterator.next();
                //融合商品实例
                offerInsts.add(offerInstVO.getOfferInst()); //融合商品实例
            }
        }
        else {
            Iterator<KitePosOfferInstVO> iterator = mainOfferInstMap.values().iterator();
            while (iterator.hasNext()) {
                KitePosOfferInstVO offerInstVO = iterator.next();
                //套餐实例
                offerInsts.add(offerInstVO.getOfferInst()); //套餐实例
            }
        }

        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
        InstType instType = sceneInst.getRootInstType();
        if (KiteStringUtils.equalsAny(sceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_ADD, LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_DEL)) {
            context.getPosDto().setDiscount(Lists.newArrayList());
            return;
        }
        offerInsts.forEach(offerInst -> {
            if (BatchAcceptUtil.isBatchSign(context.getSceneInstId())
                && KiteStringUtils.isNotEmpty(context.getOfferInstId())
                && !KiteStringUtils.equals(offerInst.getOfferInstId(), context.getOfferInstId())) {
                return;
            }
            List<KiteOfferInstDiscount> kiteOfferInstDiscounts = querySceneInstService.listOfferInstDiscounts(context.getCustId(), offerInst.getOfferInstId());
            if (Objects.isNull(kiteOfferInstDiscounts)) {
                //ErrorConsts.BUSI_CHECK_ERROR.throwOut("折扣审批信息不能为空");
                kiteOfferInstDiscounts = new ArrayList<>();
            }
            kiteOfferInstDiscounts = kiteOfferInstDiscounts.stream().filter(discount -> !KiteStringUtils.equals(discount.getActionType().name(), ActionType.X.name())).collect(Collectors.toList());
            String serviceOfferId = Optional.ofNullable(querySceneInstService.getSceneInst(context.getSceneInstId())).map(KiteSceneInst::getServiceOfferId).orElse("");

            KitePosDiscountDTO discount = new KitePosDiscountDTO();
            kiteOfferInstDiscounts.forEach(offerInstDiscount -> {
                //临时处理
                discount.setInstanceId(offerInstDiscount.getInstId());
                discount.setDiscountCode(offerInstDiscount.getDiscountOrderId());
                if ("1013".equals(serviceOfferId)) {
                    discount.setInstanceId(SeqUtils.getNext("OFFER_INST_DISCOUNT", "DISCOUNT_INST_ID"));
                }
                discount.setName(offerInstDiscount.getDiscountName());
                if(KiteStringUtils.contains(offerInstDiscount.getDiscountType(),"_")){
                    discount.setType(offerInstDiscount.getDiscountType().substring(offerInstDiscount.getDiscountType().lastIndexOf("_")+1));
                }else{
                    discount.setType(offerInstDiscount.getDiscountType());
                }
                discount.setDestItemId(offerInstDiscount.getDiscountOrderId());
                discount.setChangeType(ChangeTypeUtils.getChangeType(offerInstDiscount.getActionType().name()));
                List<KitePosAttachmentDTO> attachments = new ArrayList<KitePosAttachmentDTO>();
                KitePosAttachmentDTO attachement = new KitePosAttachmentDTO();
//                attachement.setCatagory("13"); // 服务协议
                if(KiteStringUtils.contains(offerInstDiscount.getDiscountType(),"_")){
                    attachement.setCatagory(offerInstDiscount.getDiscountType().substring(offerInstDiscount.getDiscountType().lastIndexOf("_")+1));
                }else{
                    attachement.setCatagory(offerInstDiscount.getDiscountType());
                }
                String attachementName = null;
                String attachementUrl = offerInstDiscount.getDiscountFileUrl();
                if (KiteStringUtils.contains(offerInstDiscount.getDiscountFileUrl(), "*_*")) {
                    attachementName = KiteStringUtils.substring(offerInstDiscount.getDiscountFileUrl(),
                        KiteStringUtils.lastIndexOf(offerInstDiscount.getDiscountFileUrl(), "*_*") + 3);
                    attachementUrl = KiteStringUtils.substring(attachementUrl, 0, KiteStringUtils.lastIndexOf(offerInstDiscount.getDiscountFileUrl(), "*_*"));
                } else {
                    attachementName = KiteStringUtils.substring(offerInstDiscount.getDiscountFileUrl(),
                        KiteStringUtils.lastIndexOf(offerInstDiscount.getDiscountFileUrl(), "/") + 1);
                }
                attachement.setName(attachementName);
                attachement.setUrl(attachementUrl);
                attachments.add(attachement);
                discount.setAttachments(attachments);
                discountList.add(discount);
            });
        });

        context.getPosDto().setDiscount(discountList);
    }

}
